import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:loginapp/News/NewsPage.dart';
import 'package:loginapp/Main/MainPage.dart';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:simple_animations/simple_animations.dart';
import 'package:supercharged/supercharged.dart';
import 'package:loginapp/Success/NavigationPage.dart';

enum _ColorTween { color1, color2 }
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
          primarySwatch: Colors.teal,
        ),
        home: MyHomePage(),
        routes: {
          //设置路由
          '/main': (BuildContext context) => MyHomePage(),
          '/news': (BuildContext context) => NewsPage(),
          '/Main': (BuildContext context) => MainPage(),
          '/Navigation': (BuildContext context) => NavigationPage(),
        });
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String errorEmail = ' ';
  var emailReg =
      "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*\$"; //邮箱正则表达式
  TextEditingController usernameController = TextEditingController();
  TextEditingController userpwdController = TextEditingController(); //邮箱和密码控制器
  String errorPassword = '';
  String username = '';
  String userpwd = '';
  OutlineInputBorder outlineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(30)),
      borderSide: BorderSide(color: Colors.white70, width: 2)); //用于设置表框式样
  OutlineInputBorder focuslineInputBorder = OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(30)),
      borderSide: BorderSide(color: Colors.greenAccent, width: 2)); //用于设置表框式样
  FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    _focusNode.addListener(() {
      //增加监听事件
      username = usernameController.text;
      if (!_focusNode.hasFocus) {
        //lose焦点时
        setState(() {
          //判断邮箱格式是否正确
          if (!RegExp(emailReg).hasMatch(username)) {
            errorEmail = '邮箱格式有误';
          }
        });
      } else {
        //acquire焦点时
        setState(() {
          errorEmail = '';
        });
      }
    });
  }

  void judgePwd(value) {
    setState(() {
      if (value.length > 8) {
        errorPassword = '密码不能超过八个字符';
      }
    });
  }

  void showInfo() {
    String msg = '登录成功';
    var uname = usernameController.text;
    var upwd = userpwdController.text;
    if (uname.length == 0 || upwd.length == 0) {
      msg = '所输入内容不可为空';
    } else if (uname != 'admin@163.com') {
      msg = '邮箱输入不正确';
    } else if (upwd != 'admin') {
      msg = '密码不正确';
    }

    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_LONG,
        gravity: ToastGravity.BOTTOM,
        backgroundColor: Colors.white70,
        textColor: Colors.black);
    if (msg == '登录成功') {
      Navigator.pushNamed(context, '/news'); //转发实现
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('登录邮箱'),
        ),
        body: Padding(
            padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: Stack(
              children: <Widget>[
                Positioned.fill(child: AnimatedBackground()),
                onBottom(AnimatedWave(
                  height: 180,
                  speed: 1.0,
                )),
                onBottom(AnimatedWave(
                  height: 120,
                  speed: 0.9,
                  offset: pi,
                )),
                onBottom(AnimatedWave(
                  height: 220,
                  speed: 1.2,
                  offset: pi / 2,
                )),
                Padding(
                    padding: EdgeInsets.fromLTRB(2, 0, 2, 0),
                    child: Column(
                      children: <Widget>[
                        Text(
                          //主标题容器内容及其式样设置
                          "账号登录",
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 25,
                              fontWeight: FontWeight.bold,
                              height: 5),
                        ),
                        TextField(
                          //第一个表单组件
                          style: TextStyle(),
                          focusNode: _focusNode,
                          controller: usernameController,
                          inputFormatters: [
                            WhitelistingTextInputFormatter(
                                RegExp('[a-zA-Z0-9@.]'))
                          ], //输入白名单
                          decoration: InputDecoration(
                            counterText: errorEmail, //counterText提示内容
                            counterStyle: TextStyle(
                                color: Colors.limeAccent,
                                fontSize: 15), //Text式样 红色，15字号
                            prefixIcon: Icon(Icons.person),
                            hintText: '请输入邮箱名', //表框内的提示信息
                            hintStyle:
                                TextStyle(color: Colors.white, fontSize: 15),
                            enabledBorder: outlineInputBorder,
                            focusedBorder: focuslineInputBorder,
                          ),
                        ),
                        TextField(
                          controller: userpwdController,
                          onChanged: (value) {
                            userpwd = value;
                            //调用判断密码长度
                            judgePwd(value);
                          },
                          obscureText: true,
                          decoration: InputDecoration(
                              counterText: errorPassword,
                              counterStyle: TextStyle(
                                  color: Colors.limeAccent, fontSize: 15),
                              prefixIcon: Icon(Icons.lock_open_outlined),
                              hintText: '请输入密码',
                              hintStyle:
                                  TextStyle(color: Colors.white, fontSize: 15),
                              enabledBorder: outlineInputBorder,
                              focusedBorder: focuslineInputBorder),
                        ), //密码表单
                        RaisedButton(
                            child: Text('登 录'),
                            onPressed: () {
                              showInfo();
                            },
                            color: Colors.tealAccent),
                        // RaisedButton(
                        //     child: Text('测试按钮（不上线正式服）'),
                        //     onPressed: () {
                        //       Navigator.pushNamed(context, '/news'); //转发实现
                        //     },
                        //     color: Colors.blue),
                        // Text('忘记密码|注册')
                        GestureDetector(
                          onTap: () {
                            Navigator.pushNamed(context, '/Main');
                          },
                          child: Text(
                            "没有账户？现在注册",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 15,
                                fontStyle: FontStyle.normal),
                          ),
                        ),
                      ],
                    ))
              ],
            )),
      resizeToAvoidBottomInset: false
    );
  }

  onBottom(Widget child) => Positioned.fill(
        child: Align(
          alignment: Alignment.bottomCenter,
          child: child,
        ),
      );
}

class AnimatedWave extends StatelessWidget {
  final double? height;
  final double? speed;
  final double offset;

  AnimatedWave({this.height, this.speed, this.offset = 0.0});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      return Container(
        height: height,
        width: constraints.biggest.width,
        child: LoopAnimation<double>(
            duration: (5000 / speed!).round().milliseconds,
            tween: 0.0.tweenTo(2 * pi),
            builder: (context, child, value) {
              return CustomPaint(
                foregroundPainter: CurvePainter(value + offset),
              );
            }),
      );
    });
  }
}

class CurvePainter extends CustomPainter {
  final double value;

  CurvePainter(this.value);

  @override
  void paint(Canvas canvas, Size size) {
    final white = Paint()..color = Colors.white.withAlpha(60);
    final path = Path();

    final y1 = sin(value);
    final y2 = sin(value + pi / 2);
    final y3 = sin(value + pi);

    final startPointY = size.height * (0.5 + 0.4 * y1);
    final controlPointY = size.height * (0.5 + 0.4 * y2);
    final endPointY = size.height * (0.5 + 0.4 * y3);

    path.moveTo(size.width * 0, startPointY);
    path.quadraticBezierTo(
        size.width * 0.5, controlPointY, size.width, endPointY);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.close();
    canvas.drawPath(path, white);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return true;
  }
}

class AnimatedBackground extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final tween = MultiTween<_ColorTween>()
      ..add(
        _ColorTween.color1,
        Color(0xffD38312).tweenTo(Colors.lightBlue.shade900),
        3.seconds,
      )
      ..add(
        _ColorTween.color2,
        Color(0xff32A842FF).tweenTo(Colors.lightBlueAccent),
        3.seconds,
      );

    return MirrorAnimation<MultiTweenValues<_ColorTween>>(
      tween: tween,
      duration: tween.duration,
      builder: (context, child, value) {
        return Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                value.get<Color>(_ColorTween.color1),
                value.get<Color>(_ColorTween.color2)
              ])),
        );
      },
    );
  }
}

// class NewsPage extends StatelessWidget {
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(
//       body: Center(
//         child: GestureDetector(
//           onTap: () {
//             Navigator.pushNamed(context, '/main');
//           },
//           child: Text("点击这里退出登录"),
//         ),
//       ),
//     );
//   }
// }
